package com.ncmem.up7;
import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import sun.misc.BASE64Decoder;

/**
 *
 * @author zysoft
 * 用法：
 *
 */
public class CryptoTool
{
    private String key = "2C4ED1CC9BAA42A9";
    private String iv = "2C4ED1CC9BAA42A9";
    //算法名称
    private String KEY_ALGORITHM = "AES";
    //加密算法，填充方式
    private String algorithm = "AES/CBC/NoPadding";


    public CryptoTool()
    {
    }

    public String encrypt(String data) throws Exception
    {
        try
        {
            Cipher cipher = Cipher.getInstance(this.algorithm,"BC");
            int blockSize = cipher.getBlockSize();

            //ZeroPadding
            byte[] dataBytes = data.getBytes();
            int plaintextLength = dataBytes.length;
            if (plaintextLength % blockSize != 0) {
                plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
            }

            byte[] plaintext = new byte[plaintextLength];
            System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);

            SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), this.KEY_ALGORITHM);
            IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());

            cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
            byte[] encrypted = cipher.doFinal(plaintext);

            return new sun.misc.BASE64Encoder().encode(encrypted);

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public String decrypt(String data) throws Exception
    {
        try
        {
            byte[] encrypted1 = new BASE64Decoder().decodeBuffer(data);

            Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance(this.algorithm,"BC");
            SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), this.KEY_ALGORITHM);
            IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());

            cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);

            byte[] original = cipher.doFinal(encrypted1);
            String originalString = new String(original);
            return originalString;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return null;
        }
    }
}